package com.coder520.sync_learning.demo.singleton;
/**
 * 在最后的步骤当中使用DCL双检查锁机制来实现多线程环境中的延迟加载单例设计模式
 * @author asus
 *
 */
public class SingletonDemo3 extends Thread{
	public static void main(String[] args) {
		SingletonDemo3 singletonDemo1=new SingletonDemo3();
		SingletonDemo3 singletonDemo2=new SingletonDemo3();
		SingletonDemo3 singletonDemo3=new SingletonDemo3();
		SingletonDemo3 singletonDemo4=new SingletonDemo3();
		
		singletonDemo1.start();
		singletonDemo2.start();
		singletonDemo3.start();
		singletonDemo4.start();
		
		
	}
	@Override
	public void run() {
		System.out.println(MyObject.getInstance().hashCode());
		// TODO Auto-generated method stub
	}
	static class MyObject{
		private static MyObject myObject;
		
		private MyObject() {
			
		}
		/**
		 * 使用双检测锁机制来解决问题，既保证了不需要同步代码块的异步执行性，又保证了单例的效果
		 * @return
		 *	2018年6月18日
		 */
		public static MyObject getInstance() {
			try {
				if (myObject!=null) {
					
				}else {
					Thread.sleep(3000);
					synchronized (MyObject.class) {
						if (myObject==null) {
							myObject=new MyObject();
						}
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			return myObject;
		}
	}
	// @formatter:on

}
